package com.ding.es.service;

import com.ding.es.entity.ESFilm;
import com.ding.es.repository.FilmRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ding
 * @date 2021/8/26 19:27
 */

@Service
public class ESFimlService {

    private ObjectMapper mapper = new ObjectMapper();
    @Resource
    private FilmRepository filmRepository;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public ESFilm save(ESFilm esFilm) {
        ESFilm film = filmRepository.save(esFilm);
        return film;
    }

    public List<ESFilm> search(String key) {
        SearchRequest searchRequest = new SearchRequest("film");
        searchRequest.source(SearchSourceBuilder.searchSource());
        ArrayList<ESFilm> list = new ArrayList<>();
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = searchResponse.getHits();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                System.out.println("sourceAsString = " + sourceAsString);
                ESFilm esFilm = mapper.readValue(sourceAsString, ESFilm.class);
                list.add(esFilm);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
